import tkinter as tk
import threading
import datetime
from tkinter import messagebox,simpledialog
import os
from tkinter import ttk
from tkinter import colorchooser
import json
# 文件路径
COLOR_FILE = "xixi_color.json"
def enter():
    global entry_username
    global entry_password
    root = tk.Tk()
    root.title("登陆注册页面")
    root.configure(bg='#f7f4f7')
    root.geometry("400x300+700+300")
# 创建用户名和密码输入框
    label_username = tk.Label(root, text="用户名：", bg='#FCFCFC')
    label_username.pack()
    entry_username = tk.Entry(root)
    entry_username.pack()
    label_password = tk.Label(root, text="密码", bg='#FCFCFC')
    label_password.pack()
    entry_password = tk.Entry(root, show="*")
    entry_password.pack()
# 创建登录和注册按钮
    button_enter = tk.Button(root, text="登录", command=root.destroy, bg='#FCFCFC')
    button_enter.pack(pady=10)
    button_register = tk.Button(root, text="注册", command=register, bg='#FCFCFC')
    button_register.pack(pady=10)
    root.mainloop()
def login():
    username = entry_username.get()
    password = entry_password.get()
    if username == "张" and password == "123":
        messagebox.showinfo("登录成功", "欢迎进入待办事项，" + username + "!")
    else:
        messagebox.showerror("登录失败", "用户名或密码错误！")
def register():
    username = entry_username.get()
    password = entry_password.get()
    if username and password:
        messagebox.showinfo("注册成功", "注册成功，用户名：" + username + "，密码：" + password)
    else:
        messagebox.showwarning("注册失败", "请输入用户名和密码！")
enter()
class TodoItem:
    def __init__(self, title, description, deadline, priority, completed):
        self.title = title
        self.description = description
        self.deadline = deadline
        self.priority = priority
        if (completed == "False"):
            self.completed = False
        else:
            self.completed = True
    def __str__(self):
        status = "完成" if self.completed else "未完成"
        return f"标题: {self.title}\n描述: {self.description}\n截止日期: {self.deadline}\n优先级: {self.priority}\n状态: {status}"
class TodoManagerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("待办事项")
        self.root.configure(bg='#f7f4f7')
        # 创建菜单栏
        self.menu_bar = tk.Menu(root)
        # 文件菜单
        self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.file_menu.add_command(label="保存待办事项", command=self.save_todo)
        self.file_menu.add_separator()
        self.file_menu.add_command(label="退出", command=root.quit)
        self.menu_bar.add_cascade(label="文件", menu=self.file_menu)
        # 设置菜单
        self.view_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.menu_bar.add_cascade(label="视图", menu=self.view_menu)
        def set_transparency():
            transparency = simpledialog.askfloat("设置透明度", "请输入 (0.0 到 1.0:", parent=root, minvalue=0.0,
                                                 maxvalue=1.0)
            if transparency is not None:
                root.attributes('-alpha', transparency)
        self.view_menu.add_command(label="设置透明度", command=set_transparency)
        def change_bg_color():
            # 打开颜色选择器对话框
            color = colorchooser.askcolor(title="设置颜色")
            if color:
                # 更新主窗口的背景颜色
                root.config(bg=color[1])
                # 保存颜色到文件
                xixi_color(color[1])
        def xixi_color(color):
            # 将颜色保存到文件
            with open(COLOR_FILE, 'w') as f:
                json.dump({'color': color}, f)
        def load_color():
            # 从文件加载颜色设置
            try:
                with open(COLOR_FILE, 'r') as f:
                    data = json.load(f)
                    root.config(bg=data['color'])
            except FileNotFoundError:
                pass  # 如果文件不存在，则默认背景色
            # 加载之前保存的颜色设置
        load_color()
        self.view_menu.add_command(label="设置颜色", command=change_bg_color)
        # 提醒菜单
        self.reminder_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.reminder_menu.add_command(label="设置提醒", command=self.set_reminder)
        self.menu_bar.add_cascade(label="提醒", menu=self.reminder_menu)
        # 将菜单栏应用到窗口
        root.config(menu=self.menu_bar)
        def new_todo_list(self):
            # 创建新的待办事项列表窗口
            todo_window = tk.Toplevel(self.root)
            todo_window.title("新建待办事项列表")
        self.todo_list = []
        self.current_index = -1
        # 待办事项列表
        self.file_path = "todo_list.txt"
        # 加载待办事项列表
        self.load_todo_list()
        self.setup_ui()
        self.show_all_tasks()
        self.sort_label = tk.Label(root, text="排序方式:", bg='#FCFCFC')
        self.sort_label.grid(row=7, column=0, sticky="w")
        self.sort_choices = ttk.Combobox(root, values=["按优先级", "按截止日期"])
        self.sort_choices.current(0)  # 默认选择第一个
        self.sort_choices.grid(row=7, column=1)
        self.sort_button = tk.Button(root, text="排序", bg='#FCFCFC', command=self.sort_tasks)
        self.sort_button.grid(row=7, column=2)
    def sort_tasks(self):
        sort_method = self.sort_choices.get()
        print(sort_method)
        if sort_method == "按截止日期":
            self.todo_list = sorted(self.todo_list.copy(), key=lambda x: x.deadline)
        elif sort_method == "按优先级":
            self.todo_list = sorted(self.todo_list.copy(), key=lambda x: x.priority)
        self.show_all_tasks()
    def setup_ui(self):
        # 标签和输入框
        tk.Label(self.root, text="标题:" ,bg='#FCFCFC').grid(row=0, column=0, padx=5, pady=5)
        vary_title_entry = tk.StringVar(self.root,value='')
        self.title_entry = tk.Entry(self.root,textvariable=vary_title_entry)
        self.title_entry.grid(row=0, column=1, padx=5, pady=5)
        tk.Label(self.root, text="描述:", bg='#FCFCFC').grid(row=1, column=0, padx=5, pady=5)
        vary_description_entry = tk.StringVar(self.root,value='')
        self.description_entry = tk.Entry(self.root,textvariable=vary_description_entry)
        self.description_entry.grid(row=1, column=1, padx=5, pady=5)
        tk.Label(self.root, text="截止日期", bg='#FCFCFC').grid(row=2, column=0, padx=5, pady=5)
        vary_deadline_entry = tk.StringVar(self.root,value='')
        self.deadline_entry = tk.Entry(self.root,textvariable=vary_deadline_entry)
        self.deadline_entry.grid(row=2, column=1, padx=5, pady=5)
        tk.Label(self.root, text="优先级:" ,bg='#FCFCFC').grid(row=3, column=0, padx=5, pady=5)
        var_priority_entry = tk.StringVar(self.root,value='')
        self.priority_entry = tk.Entry(self.root,textvariable=var_priority_entry)
        self.priority_entry.grid(row=3, column=1, padx=5, pady=5)
        # 按钮
        tk.Button(self.root, text="添加任务" ,bg='#FCFCFC', command=self.add_task).grid(row=4, column=0, columnspan=1,padx=5,
                                                                          pady=10)
        tk.Button(self.root, text="删除任务", bg='#FCFCFC', command=self.delete_task).grid(row=5, column=0, columnspan=1, padx=5,
                                                                             pady=10)
        tk.Button(self.root, text="查看所有任务", bg='#FCFCFC', command=self.show_all_tasks).grid(row=4, column=1, columnspan=1,
                                                                                    padx=5, pady=10)
        tk.Button(self.root, text="编辑任务", bg='#FCFCFC', command=self.edit_task).grid(row=6, column=0, columnspan=1, padx=5,
                                                                           pady=10)
        tk.Button(self.root, text="标记任务为完成", bg='#FCFCFC', command=self.mark_completed).grid(row=5, column=1, columnspan=1,
                                                                                      padx=5, pady=10)
        tk.Button(self.root, text="查看已完成任务", bg='#FCFCFC', command=self.show_completed_tasks).grid(row=6, column=1,
                                                                                            columnspan=1, padx=5,
                                                                                            pady=10)
        # 显示区域
        self.display_list = tk.Listbox(self.root, width=60, height=15)
        self.display_list.grid(row=10, column=0, columnspan=2, padx=5, pady=10)
    def add_task(self):
        title = self.title_entry.get()
        description = self.description_entry.get()
        deadline = self.deadline_entry.get()
        priority = self.priority_entry.get()
        if title and description and deadline and priority:
            item = TodoItem(title, description, deadline, priority,"False")
            self.todo_list.append(item)
            messagebox.showinfo("成功", "任务添加成功!")
            self.clear_entries()
            self.show_all_tasks()
        else:
            messagebox.showerror("错误", "请填写所有字段!")
    def show_all_tasks(self):
        self.display_list.delete(0, tk.END)
        for index, item in enumerate(self.todo_list):
            self.display_list.insert(tk.END, f"任务编号: {index}\n"+str(item) + "\n")
    def delete_task(self):
        self.todo_list.pop(self.display_list.curselection()[0])
        self.display_list.delete(self.display_list.curselection())
    def edit_task(self):
        index = self.get_current_index()
        if index != -1:
            edited_title = self.title_entry.get()
            edited_description = self.description_entry.get()
            edited_deadline = self.deadline_entry.get()
            edited_priority = self.priority_entry.get()
            if edited_title and edited_description and edited_deadline and edited_priority:
                self.todo_list[index].title = edited_title
                self.todo_list[index].description = edited_description
                self.todo_list[index].deadline = edited_deadline
                self.todo_list[index].priority = edited_priority
                messagebox.showinfo("成功", "任务编辑成功!")
                self.show_all_tasks()
                self.clear_entries()
            else:
                messagebox.showerror("错误", "请填写所有字段!")
    def mark_completed(self):
        index = self.get_current_index()
        if index != -1:
            self.todo_list[index].completed = True
            messagebox.showinfo("成功", "任务标记为完成!")
            self.show_all_tasks()
    def mark_completed(self):
        index = self.get_current_index()
        if index != -1:
            self.todo_list[index].completed = True
            messagebox.showinfo("成功", "任务标记为完成!")
            self.show_all_tasks()
    def save_todo(self):
        self.save_todo_list()
        messagebox.showinfo("保存", "待办事项已保存到文件。")
    def save_todo_list(self):
        with open(self.file_path, 'w', encoding='utf-8') as f:
            for todo in self.todo_list:
                f.write( "{title},{des},{deadline},{pri},{com}\n".format(title=todo.title, des=todo.description, deadline=todo.deadline,pri=todo.priority,com=todo.completed))
    def load_todo_list(self):
        if os.path.exists(self.file_path):
            with open(self.file_path, 'r', encoding='utf-8') as f:
                for line in f.readlines():
                    line = line.strip()
                    todo = line.split(',')
                    todoitem = TodoItem(todo[0], todo[1], todo[2], todo[3], todo[4])
                    self.todo_list.append(todoitem)
    def set_reminder(self):
        reminder_window = tk.Toplevel()
        reminder_window.configure(bg='#f7f4f7')
        reminder_window.title("设置提醒")
        def show_reminder():
            message = reminder_entry.get()
            reminder_time = reminder_time_entry.get()
            if message and reminder_time:
                try:
                    # 解析用户输入的时间
                    reminder_datetime = datetime.datetime.strptime(reminder_time, "%Y-%m-%d %H:%M")
                    # 计算当前时间和提醒时间的时间差
                    delta = (reminder_datetime - datetime.datetime.now()).total_seconds()
                    if delta > 0:
                        # 启动定时器，到时提醒
                        reminder_timer = threading.Timer(delta, lambda: messagebox.showinfo("提醒", message))
                        reminder_timer.start()
                        messagebox.showinfo("设置成功", f"提醒将在 {reminder_time} 提醒。")
                        reminder_window.destroy()
                    else:
                        messagebox.showerror("错误", "提醒时间必须是未来的时间。")
                except ValueError:
                    messagebox.showerror("错误", "请输入正确的时间格式：YYYY-MM-DD HH:MM")
        reminder_label = tk.Label(reminder_window, text="输入提醒消息:")
        reminder_label.pack(pady=10)
        reminder_entry = tk.Entry(reminder_window, width=30)
        reminder_entry.pack(pady=10)
        reminder_time_label = tk.Label(reminder_window, text="输入提醒时间（YYYY-MM-DD HH:MM）")
        reminder_time_label.pack(pady=10)
        reminder_time_entry = tk.Entry(reminder_window, width=30)
        reminder_time_entry.pack(pady=10)
        remind_button = tk.Button(reminder_window, text="设置提醒", command=show_reminder)
        remind_button.pack(pady=10)
    def show_completed_tasks(self):
        self.display_list.delete(0, tk.END)
        for index, item in enumerate(self.todo_list):
            if item.completed:
                self.display_list.insert(tk.END, f"任务编号: {index}\n" + str(item) + "\n")
    def get_current_index(self):
        try:
            index = self.display_list.curselection()[0]
            if 0 <= index < len(self.todo_list):
                self.current_index = index
                return index
            else:
                messagebox.showerror("错误", "无效的任务编号!")
                return -1
        except ValueError:
            messagebox.showerror("错误", "请输入有效的任务编号!")
            return -1
    def clear_entries(self):
        self.title_entry.delete(0, tk.END)
        self.description_entry.delete(0, tk.END)
        self.deadline_entry.delete(0, tk.END)
        self.priority_entry.delete(0, tk.END)
def main():
    root = tk.Tk()
    app = TodoManagerApp(root)
    root.mainloop()
    print()
if __name__ == "__main__":
    main()


